package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.respons.QyWeChartPushRs;
import com.xmy.cultivate.service.IQyWacherService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.article.NewArticle;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QyWacherServiceImpl implements IQyWacherService {

    private final WxCpService wxCpService;

    @Autowired
    public QyWacherServiceImpl(WxCpService wxCpService) {
        this.wxCpService = wxCpService;
    }

    @Override
    public String getUserId(String mobile) throws WxErrorException {
        String result = wxCpService.getUserService().getUserId(mobile);
        return result;
    }

    /**
     * 发送文本信息
     * @param qyWeChartPushRs
     */
    public void pushTxtContent(QyWeChartPushRs qyWeChartPushRs){
        try {
            if (StringUtils.isNotBlank(qyWeChartPushRs.getToUser())) {
                WxCpMessage message = WxCpMessage.TEXT().toUser(qyWeChartPushRs.getToUser()) // 接收消息的用户 ID，多个用|分隔
                    .agentId(wxCpService.getWxCpConfigStorage().getAgentId())
                    .content(qyWeChartPushRs.getContent())
                    .build();
                wxCpService.getMessageService().send(message);
            }
        } catch (WxErrorException e) {
        }
    }

    /**
     * 发放一条卡片信息
     * @param qyWeChartPushRs
     * @throws WxErrorException
     */
    @Override
    public void pushCardContent(QyWeChartPushRs qyWeChartPushRs) throws WxErrorException {
        try {
            if (StringUtils.isNotBlank(qyWeChartPushRs.getToUser())) {
                // 创建图文列表
                List<NewArticle> articles = new ArrayList<>();

                // 创建一条图文消息
                NewArticle article1 = new NewArticle();
                article1.setTitle(qyWeChartPushRs.getTitle());
                StringBuilder stringBuilder = new StringBuilder();
                if (StringUtils.isNotBlank(qyWeChartPushRs.getDateTime())){
                    stringBuilder.append("<div class=\"gray\">"+qyWeChartPushRs.getDateTime()+"</div>");
                }
                if (StringUtils.isNotBlank(qyWeChartPushRs.getContent())){
                    stringBuilder.append("<div class=\"normal\">"+qyWeChartPushRs.getContent()+"</div>");
                }

                if (StringUtils.isNotBlank(qyWeChartPushRs.getRemark())){
                    stringBuilder.append("<div class=\"highlight\">"+qyWeChartPushRs.getRemark()+"</div>");
                }
                article1.setDescription(stringBuilder.toString());
                //article1.setDescription("恭喜你抽中iPhone 7一台，领奖码：xxxx");
                if (StringUtils.isNotBlank(qyWeChartPushRs.getLinkUrl())){
                    article1.setUrl(qyWeChartPushRs.getLinkUrl());
                }
                //article1.setPicUrl("https://example.com/article1");
                //article1.setPagepath("https://example.com/article1");

                articles.add(article1);
                // 构建图文消息
                WxCpMessage message = WxCpMessage.NEWS()
                        .toUser(qyWeChartPushRs.getToUser()) // 接收消息的用户 ID，多个用 | 分隔
                        .agentId(wxCpService.getWxCpConfigStorage().getAgentId())
                        .articles(articles)
                        .build();
                wxCpService.getMessageService().send(message);
            }
            //System.out.println("消息发送成功");
        } catch (WxErrorException e) {
            System.err.println("消息发送失败: " + e.getError().getErrorMsg());
        }
    }




    public void doSomething2() throws WxErrorException {
        WxCpMessage message = WxCpMessage.TEXT().toUser("HuangLiMin") // 接收消息的用户 ID，多个用 | 分隔
                .agentId(wxCpService.getWxCpConfigStorage().getAgentId())
                .content("这是一条测试文本消息")
                .build();

        try {
            wxCpService.getMessageService().send(message);
            System.out.println("消息发送成功");
        } catch (WxErrorException e) {
            System.err.println("消息发送失败: " + e.getError().getErrorMsg());
        }
    }

    public void doSomething3() throws WxErrorException {
        // 创建图文列表
        List<NewArticle> articles = new ArrayList<>();

        // 创建一条图文消息
        NewArticle article1 = new NewArticle();
        article1.setTitle("有退费信息需要处理");
        article1.setDescription("<div class=\"gray\">2025年4月19日</div> <div class=\"normal\">林艳娇，八年级【陈雨欣】八（5）班，退课时21课时</div><div class=\"highlight\">请尽快处理</div>");
        //article1.setDescription("恭喜你抽中iPhone 7一台，领奖码：xxxx");
        article1.setUrl("http://teacher.5ixmy.xyz");
        //article1.setPicUrl("https://example.com/article1");
        //article1.setPagepath("https://example.com/article1");

        articles.add(article1);

        // 构建图文消息
        WxCpMessage message = WxCpMessage.NEWS()
                .toUser("HuangLiMin|LiuJia") // 接收消息的用户 ID，多个用 | 分隔
                .agentId(wxCpService.getWxCpConfigStorage().getAgentId())
                .articles(articles)
                .build();

        try {
            wxCpService.getMessageService().send(message);
            System.out.println("消息发送成功");
        } catch (WxErrorException e) {
            System.err.println("消息发送失败: " + e.getError().getErrorMsg());
        }
    }

    public List<WxCpDepart> getDepartmentList(){
        try {
            // 获取全量部门列表，不指定部门 ID 则获取所有部门
            List<WxCpDepart> departList = wxCpService.getDepartmentService().list(null);
            for (WxCpDepart depart : departList) {
                System.out.println("部门 ID: " + depart.getId());
                System.out.println("部门名称: " + depart.getName());
                System.out.println("父部门 ID: " + depart.getParentId());
                System.out.println("部门排序: " + depart.getOrder());
                System.out.println("----------------------");
                this.getUserByDepartmentList(depart.getId());
            }
            return  departList;
        } catch (WxErrorException e) {
            System.err.println("获取部门列表失败: " + e.getError().getErrorMsg());
        }
        return null;
    }

    public List<WxCpUser> getUserByDepartmentList(Long departmentId){
        try {
            // 是否递归获取子部门成员，1 表示递归获取，0 表示只获取本部门成员
            Integer fetchChild = 0;
            // 获取全量部门列表，不指定部门 ID 则获取所有部门
            List<WxCpUser> wxCpUserList = wxCpService.getUserService().listByDepartment(departmentId,false,fetchChild);

            for (WxCpUser wxCpUser : wxCpUserList) {
                // 根据成员的 userid 获取成员详情
                WxCpUser userDetail = wxCpService.getUserService().getById(wxCpUser.getUserId());
                System.out.println("用户姓名: " + userDetail.getName());
                System.out.println("用户账号: " + userDetail.getUserId());
                System.out.println("用户邮箱: " + userDetail.getEmail());
                System.out.println("用户手机号: " + userDetail.getMobile());
                System.out.println("------------------------");
            }
        } catch (WxErrorException e) {
            System.err.println("获取部门列表失败: " + e.getError().getErrorMsg());
        }
        return null;
    }


    public void getDepartmentUserList(Long departmentId) throws WxErrorException {
        // 是否递归获取子部门成员，1 表示递归获取，0 表示仅获取本部门成员
        boolean fetchChild = true;
        // 是否获取详细信息，1 表示获取详细信息，0 表示仅获取基本信息
        Integer details = 1;
        List<WxCpUser> userList = wxCpService.getUserService().listByDepartment(departmentId, fetchChild, details);

        for (WxCpUser user : userList) {
            System.out.println("用户 ID: " + user.getUserId());
            System.out.println("姓名: " + user.getName());
            System.out.println("手机号码: " + user.getMobile());
            System.out.println("邮箱: " + user.getEmail());
            System.out.println("----------------------");
        }
    }


}
